/*
 * Classse base de conexão com Banco de Dados
 * 
 */

package br.com.caelum.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author menandro.neto
 */
public class DBTest {
    protected String databaseName;
    protected String serverName;
    protected String userName;
    protected String password;
    protected String driverName;
    protected String databaseURL;
    
    public DBTest() {
        // Inicializa os parametros de composição da string de conexão
        this.databaseName = 
            this.serverName = 
            this.userName = 
            this.password = 
            this.driverName = "";
    }
    
    private Boolean emptyParameters() {
        // Testa a conexão
        return (    this.databaseName.isEmpty()
                 || this.serverName.isEmpty()
                 || this.userName.isEmpty()
                 || this.password.isEmpty()
                 || this.driverName.isEmpty() );
    }

    public Boolean testConnection() throws SQLException{
        Connection connectionTest = null;
        Boolean result = false;
        if ( this.emptyParameters() )
            return(result);
        
        try {
            connectionTest = this.getConnection();
        }
        catch(SQLException e) {
            return(result);
        }
        finally{
            result = !( connectionTest == null );
            if ( result ) 
                connectionTest.close();
        }
        
        return( result );
    }
    
    public Connection getConnection() throws SQLException {
        
        if ( this.emptyParameters() )
            return( null );
        
        try {
            Class.forName(this.driverName);
            return ( DriverManager.getConnection(this.databaseURL, 
                        this.userName, this.password) );
        }
        catch(ClassNotFoundException e) {
            throw new SQLException(e.getMessage());
        }
    }
    
}
